var START_DATE = "STARTDATE";
var END_DATE = "ENDDATE";
var USER_ID = "USER_ID";
var JSON_FROM = "d_from";
var JSON_TO = "d_to";
var TABLE_FROM = "from";
var TABLE_TO = "to";
var TABLE_LONGDATE = "longDate";
var TABLE_SUBTYPE = "subType";
var EVENTS = "events";
var TRANSACTIONS = "transactions";
var CONTRACT_ID = "contractId";
var TABLE_REF_ID = "refId";


function main( json ) {

 // var json = pp.getQueryParameters().getFirst("json");
  if ( json == null ){
        var ex = "{ exception: { message: 'no param provided'} }";
        return ex;
  }
 // var jsonObject = new JSONObject( json );
  
  //return getFilteredTransactions(jsonObject);
  var filteredTransactions = getFilteredTransactions(json);
  
  var result = new JSONObject();
  result.put (TRANSACTIONS,filteredTransactions);
return result.toString();
}



function getFilteredTransactions(jsonObject) {
  
  var records = new JSONArray();
 
  //return createTransactionCmd(jsonObject);
var json = createTransactionJsonFilter(jsonObject);
 var cmd = createTransactionCmd(jsonObject);
  
  //return json;
    EntityManager.find(  
    cmd,  
    json,
     function(result) {
      
      for( var i = 0; i < result.size() ; ++i ) {
        
        records.put( JSONObject.wrap(result.get(i)) );
      }
      
    });
    
    var result = new JSONObject();
    
    result.put( "records", records );
    
    return records ;

}


function createTransactionJsonFilter(jsonObject){

  var o = new JSONObject();   
  var attributes;
  var title;
  var userId;
 /*
  if (jsonObject.has('attributes')) 
      attributes = jsonObject.get('attributes');
  
  if ( attributes.has('title')){
      title = attributes.get('title');
      o.put('title',title);
  }
  */
  if (jsonObject.has(USER_ID)) {
      userId = jsonObject.get(USER_ID);
      o.put('userId',userId);
  }
  
 
  var cal1 = java.util.Calendar.getInstance();
  cal1.setTimeInMillis(jsonObject.get(START_DATE));
  var startDate = cal1.getTimeInMillis();
  
  var cal2 = java.util.Calendar.getInstance();
  cal2.setTimeInMillis(jsonObject.get(END_DATE));
  var endDate = cal2.getTimeInMillis();
 
  o.put('l_STARTDATE', startDate);
  o.put('l_ENDDATE',endDate);
  
  return o;
}

function createTransactionCmd(jsonObject){

 var cmd = "select t from TransactionEntity t where t.longDate >= :l_STARTDATE and t.longDate < :l_ENDDATE";
 // var cmd = "select t from TransactionEntity t where t.longDate > :STARTDATE";
 /*
  if ( jsonObject.has('contractId'))
    cmd += " and t.contractId = :contractId";
*/
  if ( jsonObject.has('USER_ID'))
    cmd += " and t.userId = :userId";

  return cmd;
}
